using System;
using Cysharp.Threading.Tasks;
using Framework.Interface;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Game.Logic.App
{
    public class Startup : MonoBehaviour
    {
        public EventSystem eventSystem;
        public Transform uiRoot;
        
        private GameObject hotfixView;
        private App app;
        
        private async void Awake()
        {
            EventsManager.Instance.Add<EnterGame>(OnHotfixCompeted);
            await LoadHotfix();
            await LoadApp();
        }

        private void OnEnable()
        {
            if (eventSystem != null)
                eventSystem.enabled = true;
        }

        // 加载hotfix界面
        private async UniTask LoadHotfix()
        {
            GameObject prefab = await Resources.LoadAsync<GameObject>("Prefabs/Hotfix/HotfixView") as GameObject;
            hotfixView = Instantiate(prefab, uiRoot, false);
        }
        
        // 加载脚本启动
        private async UniTask LoadApp()
        {
            if (app != null)
                return;
            
            GameObject prefab = await Resources.LoadAsync<GameObject>("Prefabs/App") as GameObject;
            GameObject appObj = Instantiate(prefab);
            if (appObj != null)
            {
                appObj.name = "App";
                app = appObj.GetComponent<App>();
            }
        }

        private void OnHotfixCompeted(IListener listener)
        {
            if (hotfixView != null)
                hotfixView.gameObject.SetActive(false);
            if (eventSystem != null)
                eventSystem.enabled = false;
        }

        private void OnDestroy()
        {
            EventsManager.Instance.Remove<EnterGame>(OnHotfixCompeted);
            if (hotfixView != null)
                Destroy(hotfixView);
        }
    }
}